<?php
require_once __DIR__ . '/../functions.php';
require_once __DIR__ . '/../pushplus.php';

// 检查管理员权限
if (!isAdmin()) {
    redirect('../index.php', '您没有权限访问此页面', 'danger');
}

// 防重复提交token
if (!isset($_SESSION['form_tokens'])) {
    $_SESSION['form_tokens'] = [];
}

// 生成新的token
$currentToken = md5(uniqid(mt_rand(), true) . $_SERVER['REMOTE_ADDR']);
$_SESSION['form_tokens'][] = $currentToken;
// 保持最近50个token
if (count($_SESSION['form_tokens']) > 200) {
    array_shift($_SESSION['form_tokens']);
}

// 获取筛选条件
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$user_id = $_GET['user_id'] ?? '';
$delivery_location = $_GET['delivery_location'] ?? '';
$order_platform = $_GET['order_platform'] ?? '';
$payment_method = $_GET['payment_method'] ?? '';
$group_name = $_GET['group_name'] ?? '';
$is_registered = $_GET['is_registered'] ?? '';
$settlement_type = $_GET['settlement_type'] ?? '';
$is_returned = $_GET['is_returned'] ?? '';
$is_signed = $_GET['is_signed'] ?? '';
$is_refunded = $_GET['is_refunded'] ?? ''; // 新增：回款状态筛选
$operation_type = $_GET['operation_type'] ?? ''; // 新增：操作类型筛选
$last_operation_start = $_GET['last_operation_start'] ?? ''; // 新增：最后操作开始时间
$last_operation_end = $_GET['last_operation_end'] ?? ''; // 新增：最后操作结束时间
$sort_by = $_GET['sort_by'] ?? 'created_at'; // 新增：排序字段
$sort_order = $_GET['sort_order'] ?? 'desc'; // 新增：排序方式
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = intval($_GET['per_page'] ?? 30);

// 获取配置选项
$deliveryLocations = getConfigOptions('delivery_location');
$orderPlatforms = getConfigOptions('order_platform');
$groupOptions = getConfigOptions('group_name');

// 构建查询条件
$where = ['1=1'];
$params = [];

if ($search) {
    $where[] = '(o.product_name LIKE ? OR o.tracking_no LIKE ? OR u.username LIKE ? OR u.phone LIKE ?)';
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status && in_array($status, ['pending', 'settled', 'refunded'])) {
    $where[] = 'o.status = ?';
    $params[] = $status;
}

if ($user_id) {
    $where[] = 'o.user_id = ?';
    $params[] = intval($user_id);
}

if ($delivery_location) {
    $where[] = 'o.delivery_location = ?';
    $params[] = $delivery_location;
}

if ($order_platform) {
    $where[] = 'o.order_platform = ?';
    $params[] = $order_platform;
}

if ($payment_method) {
    $where[] = 'o.payment_method = ?';
    $params[] = $payment_method;
}

if ($group_name) {
    $where[] = 'u.group_name = ?';
    $params[] = $group_name;
}

if ($is_registered !== '') {
    $where[] = 'o.is_registered = ?';
    $params[] = intval($is_registered);
}

if ($settlement_type) {
    if ($settlement_type == 'none') {
        $where[] = '(o.settlement_type = "none" OR o.settlement_type IS NULL)';
    } else {
        $where[] = 'o.settlement_type = ?';
        $params[] = $settlement_type;
    }
}

if ($is_returned !== '') {
    $where[] = 'o.is_returned = ?';
    $params[] = intval($is_returned);
}

if ($is_signed !== '') {
    $where[] = 'o.is_signed = ?';
    $params[] = intval($is_signed);
}

// 新增：回款状态筛选
if ($is_refunded !== '') {
    $where[] = 'o.is_refunded = ?';
    $params[] = intval($is_refunded);
}

// 新增：操作类型筛选
if ($operation_type) {
    $where[] = 'o.id IN (SELECT order_id FROM order_operations WHERE operation_type = ?)';
    $params[] = $operation_type;
}

// 新增：最后操作时间范围筛选
if ($last_operation_start && $last_operation_end) {
    $where[] = 'o.id IN (SELECT order_id FROM order_operations WHERE created_at BETWEEN ? AND ?)';
    $params[] = $last_operation_start;
    $params[] = $last_operation_end;
} elseif ($last_operation_start) {
    $where[] = 'o.id IN (SELECT order_id FROM order_operations WHERE created_at >= ?)';
    $params[] = $last_operation_start;
} elseif ($last_operation_end) {
    $where[] = 'o.id IN (SELECT order_id FROM order_operations WHERE created_at <= ?)';
    $params[] = $last_operation_end;
}

$whereClause = implode(' AND ', $where);

// 构建排序
$orderBy = '';
switch ($sort_by) {
    case 'username':
        $orderBy = 'u.username';
        break;
    case 'phone':
        $orderBy = 'u.phone';
        break;
    case 'order_amount':
        $orderBy = 'o.order_amount';
        break;
    case 'product_name':
        $orderBy = 'o.product_name';
        break;
    case 'created_at':
    default:
        $orderBy = 'o.created_at';
        break;
}

$orderBy .= ' ' . ($sort_order === 'asc' ? 'ASC' : 'DESC');

// 获取订单总数
$db = getDB();
$stmt = $db->prepare("SELECT COUNT(*) FROM orders o LEFT JOIN users u ON o.user_id = u.id WHERE $whereClause");
$stmt->execute($params);
$total = $stmt->fetchColumn();

// 计算分页
$totalPages = ceil($total / $perPage);
$page = min($page, $totalPages ?: 1);
$offset = ($page - 1) * $perPage;

// 获取订单列表（带排序）
$stmt = $db->prepare("SELECT o.*, u.username, u.phone, u.group_name FROM orders o 
                     LEFT JOIN users u ON o.user_id = u.id 
                     WHERE $whereClause 
                     ORDER BY $orderBy 
                     LIMIT $offset, $perPage");
$stmt->execute($params);
$orders = $stmt->fetchAll();

// 获取统计信息
$statsStmt = $db->query("SELECT 
    COUNT(*) as total_orders,
    SUM(order_amount) as total_amount,
    COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_orders,
    COUNT(CASE WHEN status = 'settled' THEN 1 END) as settled_orders,
    COUNT(CASE WHEN status = 'refunded' THEN 1 END) as refunded_orders,
    COUNT(CASE WHEN is_refunded = 1 THEN 1 END) as refunded_count, 
    SUM(CASE WHEN status = 'settled' AND settlement_amount > 0 THEN settlement_amount ELSE 0 END) as settled_amount
FROM orders");
$orderStats = $statsStmt->fetch();

// 处理订单状态变更
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $submittedToken = $_POST['form_token'] ?? '';
    
    // 检查token是否有效
    if (empty($submittedToken) || !in_array($submittedToken, $_SESSION['form_tokens'])) {
        $error = '表单令牌无效，请刷新页面后重试';
    } else {
        // 移除已使用的token
        $_SESSION['form_tokens'] = array_diff($_SESSION['form_tokens'], [$submittedToken]);
        
        // 原有的处理逻辑...
        $action = $_POST['action'];
        $orderId = intval($_POST['order_id'] ?? 0);
        
        if ($orderId <= 0) {
            $error = '订单ID无效';
        } else {
        if ($action == 'update_status') {
            $operationType = $_POST['operation_type'] ?? '';
            $settlementAmount = $_POST['settlement_amount'] ?? null;
            $settlementInfo = $_POST['settlement_info'] ?? '';
            $isRegistered = isset($_POST['is_registered']) ? intval($_POST['is_registered']) : null;
            $isSigned = isset($_POST['is_signed']) ? intval($_POST['is_signed']) : null;
            
            // 获取基本信息的更新
            $productName = $_POST['product_name'] ?? '';
            $deliveryLocation = $_POST['delivery_location'] ?? '';
            $orderPlatform = $_POST['order_platform'] ?? '';
            $trackingNo = $_POST['tracking_no'] ?? '';
            $orderAmount = $_POST['order_amount'] ?? 0;
            $paymentMethod = $_POST['payment_method'] ?? '';
            $orderNotes = $_POST['order_notes'] ?? '';
            
            // 获取订单信息
            $stmt = $db->prepare("SELECT * FROM orders WHERE id = ?");
            $stmt->execute([$orderId]);
            $order = $stmt->fetch();
            
            if (!$order) {
                $error = '订单不存在';
            } elseif ($order['status'] == 'refunded' && $operationType == 'return') {
                $error = '该订单已退还，无法重复退还';
            } elseif ($order['is_registered'] == 1 && $operationType == 'register') {
                $error = '该订单已登记，无法重复登记';
            } else {
                // 处理订单截图上传
                $orderScreenshot = $order['order_screenshot'];
                if (isset($_FILES['order_screenshot']) && $_FILES['order_screenshot']['error'] === UPLOAD_ERR_OK) {
                    $uploadResult = uploadFile($_FILES['order_screenshot'], 'order_screenshot');
                    if ($uploadResult['success']) {
                        // 删除旧截图
                        if ($orderScreenshot) {
                            deleteFile($orderScreenshot, 'order_screenshot');
                        }
                        $orderScreenshot = $uploadResult['filename'];
                    }
                }
                
                // 处理结算截图上传
                $settlementScreenshots = [];
                if (isset($_FILES['settlement_screenshots']) && is_array($_FILES['settlement_screenshots']['name'])) {
                    foreach ($_FILES['settlement_screenshots']['name'] as $key => $name) {
                        if ($_FILES['settlement_screenshots']['error'][$key] === UPLOAD_ERR_OK) {
                            $file = [
                                'name' => $name,
                                'type' => $_FILES['settlement_screenshots']['type'][$key],
                                'tmp_name' => $_FILES['settlement_screenshots']['tmp_name'][$key],
                                'error' => $_FILES['settlement_screenshots']['error'][$key],
                                'size' => $_FILES['settlement_screenshots']['size'][$key]
                            ];
                            
                            $uploadResult = uploadFile($file, 'settlement_screenshot');
                            if ($uploadResult['success']) {
                                $settlementScreenshots[] = $uploadResult['filename'];
                            }
                        }
                    }
                }
                
                if (!isset($error)) {
                    // 开始事务
                    $db->beginTransaction();
                    
                    try {
                        $updates = [];
                        $updateParams = [];
                        
                        // 更新基本信息
                        $updates[] = 'product_name = ?';
                        $updateParams[] = $productName;
                        
                        $updates[] = 'delivery_location = ?';
                        $updateParams[] = $deliveryLocation;
                        
                        $updates[] = 'order_platform = ?';
                        $updateParams[] = $orderPlatform;
                        
                        $updates[] = 'tracking_no = ?';
                        $updateParams[] = $trackingNo;
                        
                        $updates[] = 'order_amount = ?';
                        $updateParams[] = floatval($orderAmount);
                        
                        $updates[] = 'payment_method = ?';
                        $updateParams[] = $paymentMethod;
                        
                        $updates[] = 'notes = ?';
                        $updateParams[] = $orderNotes;
                        
                        $updates[] = 'order_screenshot = ?';
                        $updateParams[] = $orderScreenshot;
                        
                        // 根据操作类型更新相应字段
                        switch ($operationType) {
                            case 'update_info':
                                // 只更新基本信息，不改变任何状态字段
                                // 这里不需要添加任何状态更新
                                break;
                                
                            case 'register':
                                if ($order['is_registered'] == 1) {
                                    throw new Exception('该订单已登记，无法重复登记');
                                }
                                $updates[] = 'is_registered = 1';
                                break;
                            case 'settle_principal':
                                $updates[] = 'is_registered = 1';
                                $updates[] = 'settlement_type = "principal"';
                                $updates[] = 'status = "settled"';
                                if ($settlementAmount) {
                                    $updates[] = 'settlement_amount = ?';
                                    $updateParams[] = $settlementAmount;
                                }
                                break;
                            case 'settle_commission':
                                $updates[] = 'is_registered = 1';
                                $updates[] = 'settlement_type = "principal_commission"';
                                $updates[] = 'status = "settled"';
                                if ($settlementAmount) {
                                    $updates[] = 'settlement_amount = ?';
                                    $updateParams[] = $settlementAmount;
                                }
                                break;
                            case 'return':
                                if ($order['status'] == 'refunded') {
                                    throw new Exception('该订单已退还，无法重复退还');
                                }
                                $updates[] = 'is_registered = 1';
                                $updates[] = 'is_returned = 1';
                                $updates[] = 'status = "refunded"';
                                break;
                        }
                        
                        // 更新签收状态
                        if ($isSigned !== null) {
                            $updates[] = 'is_signed = ?';
                            $updateParams[] = $isSigned;
                        }
                        
                        // 更新结算信息
                        if ($settlementInfo) {
                            $updates[] = 'settlement_info = ?';
                            $updateParams[] = $settlementInfo;
                        }
                        
                        // 更新管理员ID
                        $updates[] = 'admin_id = ?';
                        $updateParams[] = $_SESSION['user_id'];
                        
                        // 执行更新
                        if (!empty($updates)) {
                            $updateSql = "UPDATE orders SET " . implode(', ', $updates) . " WHERE id = ?";
                            $updateParams[] = $orderId;
                            
                            $stmt = $db->prepare($updateSql);
                            if (!$stmt->execute($updateParams)) {
                                throw new Exception('订单更新失败');
                            }
                        }
                        
                        // 记录操作
                        $operationAmount = 0;
                        if ($operationType !== 'update_info') {
                            if ($settlementAmount) {
                                $operationAmount = $settlementAmount;
                            } elseif ($operationType == 'settle_principal' || $operationType == 'settle_commission') {
                                $operationAmount = $order['order_amount'];
                            }
                        } else {
                            // 对于 update_info 操作，金额设为 0 或 null
                            $operationAmount = 0;
                        }
                        
                        // 记录操作 - 对于 update_info 也记录
                        if (!recordOrderOperation($orderId, $operationType, $operationAmount, $settlementInfo, $settlementScreenshots, $_SESSION['user_id'])) {
                            throw new Exception('操作记录失败');
                        }
                        
                        // 处理结算逻辑
                        if ($operationType == 'settle_principal' || $operationType == 'settle_commission') {
                            $settleType = ($operationType == 'settle_principal') ? 'commission' : 'principal_commission';
                            if (!processOrderSettlementNew($orderId, $settleType, $operationAmount, $settlementInfo, $settlementScreenshots, $_SESSION['user_id'])) {
                            throw new Exception('结算处理失败');
                        }
                        }
                        
                        $db->commit();
                        $success = '订单操作成功完成';
                        
                    } catch (Exception $e) {
                        $db->rollback();
                        $error = $e->getMessage();
                    }
                }
            }
        } elseif ($action == 'delete') {
            // 删除订单
            $stmt = $db->prepare("SELECT * FROM orders WHERE id = ?");
            $stmt->execute([$orderId]);
            $order = $stmt->fetch();
            
            if ($order) {
                // 删除相关图片
                if ($order['order_screenshot']) {
                    deleteFile($order['order_screenshot'], 'order_screenshot');
                }
                
                // 删除操作记录中的图片
                $stmt = $db->prepare("SELECT screenshots FROM order_operations WHERE order_id = ?");
                $stmt->execute([$orderId]);
                $operations = $stmt->fetchAll();
                foreach ($operations as $op) {
                    if ($op['screenshots']) {
                        $screenshots = json_decode($op['screenshots'], true);
                        foreach ($screenshots as $screenshot) {
                            deleteFile($screenshot, 'settlement_screenshot');
                        }
                    }
                }
                
                // 删除操作记录
                $stmt = $db->prepare("DELETE FROM order_operations WHERE order_id = ?");
                $stmt->execute([$orderId]);
                
                // 删除订单
                $stmt = $db->prepare("DELETE FROM orders WHERE id = ?");
                if ($stmt->execute([$orderId])) {
                    $success = '订单删除成功';
                } else {
                    $error = '订单删除失败';
                }
            }
        }
    
            if (!isset($error) && isset($success)) {
                // 构建重定向URL，保留筛选条件
                $redirectParams = $_GET;
                $_SESSION['flash_message'] = [
                    'type' => 'success',
                    'message' => $success
                ];
                $redirectUrl = 'orders.php?' . http_build_query($redirectParams);
                header('Location: ' . $redirectUrl);
                exit;
            }
        }
        }
    }
    // 重新获取订单列表
    $stmt = $db->prepare("SELECT o.*, u.username, u.phone, u.group_name FROM orders o 
                         LEFT JOIN users u ON o.user_id = u.id 
                         WHERE $whereClause 
                         ORDER BY $orderBy 
                         LIMIT $offset, $perPage");
    $stmt->execute($params);
    $orders = $stmt->fetchAll();


// 获取用户列表（用于筛选）
$stmt = $db->query("SELECT id, username, phone, group_name FROM users WHERE status = 1 ORDER BY username");
$usersList = $stmt->fetchAll();

include __DIR__ . '/header.php';
?>


            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">订单管理 - 全部订单</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <div class="btn-group me-2">
                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="exportOrders()">
                            <i class="bi bi-download"></i> 导出订单
                        </button>
                    </div>
                </div>
            </div>

            <?php if (isset($error)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="bi bi-exclamation-triangle-fill"></i> <?php echo htmlspecialchars($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if (isset($success)): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="bi bi-check-circle-fill"></i> <?php echo htmlspecialchars($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- 订单统计 -->
            <div class="row mb-4">
                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-primary shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                        总订单数
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">
                                        <?php echo $orderStats['total_orders']; ?>
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <i class="bi bi-list-check fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-warning shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                        待处理订单
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $orderStats['pending_orders']; ?></div>
                                </div>
                                <div class="col-auto">
                                    <i class="bi bi-hourglass-split fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-success shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                        已结算订单
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $orderStats['settled_orders']; ?></div>
                                    <div class="text-xs text-muted mt-1">总结算: ¥<?php echo number_format($orderStats['settled_amount'], 2); ?></div>
                                </div>
                                <div class="col-auto">
                                    <i class="bi bi-check-circle-fill fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-info shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                        总订单金额
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">¥<?php echo number_format($orderStats['total_amount'], 2); ?></div>
                                    <div class="text-xs text-muted mt-1">
                                        已退还: <?php echo $orderStats['refunded_orders']; ?> 单 |
                                        已回款: <?php echo $orderStats['refunded_count']; ?> 单
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <i class="bi bi-currency-yen fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 筛选器 -->
            <div class="card mb-4">
                <div class="card-body">
                    <form method="GET" class="row g-3">
                        <div class="col-md-2">
                            <label for="search" class="form-label">搜索订单</label>
                            <input type="text" class="form-control" id="search" name="search" 
                                   placeholder="商品名、物流号、用户名、手机号" 
                                   value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <div class="col-md-2">
                            <label for="status" class="form-label">订单状态</label>
                            <select class="form-select" id="status" name="status">
                                <option value="">全部状态</option>
                                <option value="pending" <?php echo $status == 'pending' ? 'selected' : ''; ?>>未结算</option>
                                <option value="settled" <?php echo $status == 'settled' ? 'selected' : ''; ?>>已结算</option>
                                <option value="refunded" <?php echo $status == 'refunded' ? 'selected' : ''; ?>>已退还</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="is_registered" class="form-label">登记状态</label>
                            <select class="form-select" id="is_registered" name="is_registered">
                                <option value="">全部</option>
                                <option value="1" <?php echo $is_registered === '1' ? 'selected' : ''; ?>>已登记</option>
                                <option value="0" <?php echo $is_registered === '0' ? 'selected' : ''; ?>>未登记</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="settlement_type" class="form-label">结算类型</label>
                            <select class="form-select" id="settlement_type" name="settlement_type">
                                <option value="">全部</option>
                                <option value="none" <?php echo $settlement_type == 'none' ? 'selected' : ''; ?>>未结算</option>
                                <option value="principal" <?php echo $settlement_type == 'principal' ? 'selected' : ''; ?>>结本金</option>
                                <option value="principal_commission" <?php echo $settlement_type == 'principal_commission' ? 'selected' : ''; ?>>结本金+佣金</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="is_signed" class="form-label">签收状态</label>
                            <select class="form-select" id="is_signed" name="is_signed">
                                <option value="">全部</option>
                                <option value="1" <?php echo $is_signed === '1' ? 'selected' : ''; ?>>已签收</option>
                                <option value="0" <?php echo $is_signed === '0' ? 'selected' : ''; ?>>未签收</option>
                            </select>
                        </div>
                        <!-- 新增：回款状态筛选 -->
                        <div class="col-md-2">
                            <label for="is_refunded" class="form-label">回款状态</label>
                            <select class="form-select" id="is_refunded" name="is_refunded">
                                <option value="">全部</option>
                                <option value="1" <?php echo $is_refunded === '1' ? 'selected' : ''; ?>>已回款</option>
                                <option value="0" <?php echo $is_refunded === '0' ? 'selected' : ''; ?>>未回款</option>
                            </select>
                        </div>
                    </div>
                    <div class="row g-3 mt-2">
                        <!-- 新增：操作类型筛选 -->
                        <div class="col-md-2">
                            <label for="operation_type" class="form-label">操作类型</label>
                            <select class="form-select" id="operation_type" name="operation_type">
                                <option value="">全部操作</option>
                                <option value="register" <?php echo $operation_type == 'register' ? 'selected' : ''; ?>>登记</option>
                                <option value="settle_principal" <?php echo $operation_type == 'settle_principal' ? 'selected' : ''; ?>>结本金</option>
                                <option value="settle_commission" <?php echo $operation_type == 'settle_commission' ? 'selected' : ''; ?>>结本金+佣金</option>
                                <option value="return" <?php echo $operation_type == 'return' ? 'selected' : ''; ?>>退还</option>
                            </select>
                        </div>
                        <!-- 新增：最后操作时间范围筛选 -->
                        <div class="col-md-2">
                            <label for="last_operation_start" class="form-label">最后操作开始时间</label>
                            <input type="datetime-local" class="form-control" id="last_operation_start" name="last_operation_start" 
                                   value="<?php echo htmlspecialchars($last_operation_start); ?>">
                        </div>
                        <div class="col-md-2">
                            <label for="last_operation_end" class="form-label">最后操作结束时间</label>
                            <input type="datetime-local" class="form-control" id="last_operation_end" name="last_operation_end" 
                                   value="<?php echo htmlspecialchars($last_operation_end); ?>">
                        </div>
                        <div class="col-md-2">
                            <label for="user_id" class="form-label">用户筛选</label>
                            <select class="form-select" id="user_id" name="user_id">
                                <option value="">全部用户</option>
                                <?php foreach ($usersList as $user): ?>
                                    <option value="<?php echo $user['id']; ?>" 
                                            <?php echo $user_id == $user['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($user['username']); ?> (<?php echo $user['phone']; ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="delivery_location" class="form-label">收货地</label>
                            <select class="form-select" id="delivery_location" name="delivery_location">
                                <option value="">全部收货地</option>
                                <?php foreach ($deliveryLocations as $location): ?>
                                    <option value="<?php echo $location['option_value']; ?>" 
                                            <?php echo $delivery_location == $location['option_value'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($location['option_label']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="order_platform" class="form-label">下单平台</label>
                            <select class="form-select" id="order_platform" name="order_platform">
                                <option value="">全部平台</option>
                                <?php foreach ($orderPlatforms as $platform): ?>
                                    <option value="<?php echo $platform['option_value']; ?>" 
                                            <?php echo $order_platform == $platform['option_value'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($platform['option_label']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="payment_method" class="form-label">付款方式</label>
                            <select class="form-select" id="payment_method" name="payment_method">
                                <option value="">全部方式</option>
                                <option value="owner_paid" <?php echo $payment_method == 'owner_paid' ? 'selected' : ''; ?>>自己付款</option>
                                <option value="group_paid" <?php echo $payment_method == 'group_paid' ? 'selected' : ''; ?>>群主垫付</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="group_name" class="form-label">所在群组</label>
                            <select class="form-select" id="group_name" name="group_name">
                                <option value="">全部群组</option>
                                <?php foreach ($groupOptions as $group): ?>
                                    <option value="<?php echo $group['option_value']; ?>" 
                                            <?php echo $group_name == $group['option_value'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($group['option_label']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <!-- 新增：排序字段和排序方式 -->
                        <div class="col-md-2">
                            <label for="sort_by" class="form-label">排序字段</label>
                            <select class="form-select" id="sort_by" name="sort_by">
                                <option value="created_at" <?php echo $sort_by == 'created_at' ? 'selected' : ''; ?>>提交时间</option>
                                <option value="username" <?php echo $sort_by == 'username' ? 'selected' : ''; ?>>用户名</option>
                                <option value="phone" <?php echo $sort_by == 'phone' ? 'selected' : ''; ?>>手机号</option>
                                <option value="order_amount" <?php echo $sort_by == 'order_amount' ? 'selected' : ''; ?>>订单金额</option>
                                <option value="product_name" <?php echo $sort_by == 'product_name' ? 'selected' : ''; ?>>商品名称</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="sort_order" class="form-label">排序方式</label>
                            <select class="form-select" id="sort_order" name="sort_order">
                                <option value="desc" <?php echo $sort_order == 'desc' ? 'selected' : ''; ?>>降序</option>
                                <option value="asc" <?php echo $sort_order == 'asc' ? 'selected' : ''; ?>>升序</option>
                            </select>
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2">
                                <i class="bi bi-search"></i> 搜索
                            </button>
                            <a href="orders.php" class="btn btn-secondary">
                                <i class="bi bi-arrow-counterclockwise"></i> 重置
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 批量操作 -->
            <div class="card mb-4">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                                <label class="form-check-label" for="selectAll">
                                    全选本页订单
                                </label>
                            </div>
                        </div>
                        <div class="col-md-6 text-md-end">
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-sm btn-outline-success" onclick="batchSettle()">
                                    <i class="bi bi-check-circle"></i> 批量结算
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-warning" onclick="batchRefund()">
                                    <i class="bi bi-arrow-return-left"></i> 批量退还
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-danger" onclick="batchDelete()">
                                    <i class="bi bi-trash"></i> 批量删除
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 订单列表 -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>
                                        <input type="checkbox" id="checkAll" onchange="toggleAllCheckboxes()">
                                    </th>
                                    <th>ID</th>
                                    <th>商品名称</th>
                                    <th>收货地</th>
                                    <th>下单平台</th>
                                    <th>用户</th>
                                    <th>群组</th>
                                    <th>物流号</th>
                                    <th>金额</th>
                                    <th>付款方式</th>
                                    <th>登记</th>
                                    <th>结算类型</th>
                                    <th>退还</th>
                                    <th>签收</th>
                                    <!-- 新增：回款状态列 -->
                                    <th>回款</th>
                                    <th>状态</th>
                                    <th>提交时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($orders)): ?>
                                    <tr>
                                        <td colspan="18" class="text-center text-muted py-4">
                                            <i class="bi bi-inbox display-4"></i>
                                            <p class="mt-2 mb-0">暂无订单数据</p>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($orders as $order): ?>
                                        <tr>
                                            <td>
                                                <input type="checkbox" class="order-checkbox" value="<?php echo $order['id']; ?>">
                                            </td>
                                            <td><?php echo $order['id']; ?></td>
                                            <td>
                                                <span class="text-truncate-2" style="max-width: 150px; display: inline-block;">
                                                    <?php echo htmlspecialchars($order['product_name']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars(getConfigOptionLabel('delivery_location', $order['delivery_location'])); ?>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars(getConfigOptionLabel('order_platform', $order['order_platform'])); ?>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars($order['username']); ?>
                                                <br>
                                                <small class="text-muted"><?php echo htmlspecialchars($order['phone']); ?></small>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars(getConfigOptionLabel('group_name', $order['group_name'])); ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($order['tracking_no']); ?></td>
                                            <td><?php echo formatAmount($order['order_amount']); ?></td>
                                            <td>
                                                <span class="badge bg-<?php echo $order['payment_method'] == 'group_paid' ? 'warning' : 'info'; ?>">
                                                    <?php echo getPaymentMethodText($order['payment_method']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo getOrderRegistrationClass($order['is_registered']); ?>">
                                                    <?php echo getOrderRegistrationText($order['is_registered']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo getSettlementTypeClass($order['settlement_type']); ?>">
                                                    <?php echo getSettlementTypeText($order['settlement_type']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo getOrderReturnClass($order['is_returned']); ?>">
                                                    <?php echo getOrderReturnText($order['is_returned']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo getOrderSignClass($order['is_signed']); ?>">
                                                    <?php echo getOrderSignText($order['is_signed']); ?>
                                                </span>
                                            </td>
                                            <!-- 新增：回款状态显示 -->
                                            <td>
                                                <span class="badge bg-<?php echo getOrderRefundClass($order['is_refunded']); ?>">
                                                    <?php echo getOrderRefundText($order['is_refunded']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo getOrderStatusClass($order['status']); ?>">
                                                    <?php echo getOrderStatusText($order['status']); ?>
                                                </span>
                                                <?php if ($order['status'] == 'settled' && $order['settlement_amount']): ?>
                                                    <br>
                                                    <small class="text-success">
                                                        结算: <?php echo formatAmount($order['settlement_amount']); ?>
                                                    </small>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo formatTime($order['created_at']); ?></td>
                                            <td>
                                                <div class="btn-group" role="group">
                                                    <button type="button" class="btn btn-sm btn-outline-primary" 
                                                            onclick="showOrderDetails(<?php echo $order['id']; ?>)"
                                                            data-bs-toggle="tooltip" title="查看详情">
                                                        <i class="bi bi-eye"></i>
                                                    </button>
                                                    
                                                    <button type="button" class="btn btn-sm btn-outline-success" 
                                                            onclick="editOrder(<?php echo $order['id']; ?>)"
                                                            data-bs-toggle="tooltip" title="处理订单">
                                                        <i class="bi bi-pencil"></i>
                                                    </button>
                                                    
                                                    <?php if ($order['order_screenshot']): ?>
                                                        <button type="button" class="btn btn-sm btn-outline-info" 
                                                                onclick="showImageModal('<?php echo UPLOAD_URL . 'orders/' . $order['order_screenshot']; ?>')"
                                                                data-bs-toggle="tooltip" title="订单截图">
                                                            <i class="bi bi-image"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                    
                                                    <form method="POST" style="display: inline;" onsubmit="return confirm('确定要删除这个订单吗？此操作不可恢复！');">
                                                        <input type="hidden" name="action" value="delete">
                                                        <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                                        <input type="hidden" name="form_token" value="<?php echo $currentToken; ?>">
                                                        <button type="submit" class="btn btn-sm btn-outline-danger" 
                                                                data-bs-toggle="tooltip" title="删除">
                                                            <i class="bi bi-trash"></i>
                                                        </button>
                                                    </form>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页和每页显示数量 -->
                    <div class="d-flex justify-content-between align-items-center mt-4">
                        <div class="d-flex align-items-center">
                            <label for="perPage" class="form-label mb-0 me-2">每页显示：</label>
                            <select class="form-select form-select-sm" id="perPage" name="per_page" style="width: 80px;" onchange="changePerPage(this.value)">
                                <option value="30" <?php echo $perPage == 30 ? 'selected' : ''; ?>>30</option>
                                <option value="50" <?php echo $perPage == 50 ? 'selected' : ''; ?>>50</option>
                                <option value="100" <?php echo $perPage == 100 ? 'selected' : ''; ?>>100</option>
                            </select>
                        </div>
                        
                        <?php if ($totalPages > 1): ?>
                            <nav aria-label="订单分页">
                                <ul class="pagination justify-content-center mb-0">
                                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">
                                            <i class="bi bi-chevron-left"></i> 上一页
                                        </a>
                                    </li>
                                
                                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                    <?php if ($i == 1 || $i == $totalPages || ($i >= $page - 2 && $i <= $page + 2)): ?>
                                        <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                            <a class="page-link" href="?page=<?php echo $i; ?>&<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>">
                                                <?php echo $i; ?>
                                            </a>
                                        </li>
                                    <?php elseif ($i == $page - 3 || $i == $page + 3): ?>
                                        <li class="page-item disabled">
                                            <span class="page-link">...</span>
                                        </li>
                                    <?php endif; ?>
                                <?php endfor; ?>
                                
                                <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?>&<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">
                                        下一页 <i class="bi bi-chevron-right"></i>
                                    </a>
                                </li>
                            </ul>
                        </nav>
                    <?php endif; ?>
                </div>
            </div>

<!-- 图片放大模态框 -->
<div class="modal fade" id="imageModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">图片预览</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center">
                <img id="modalImage" src="" class="img-fluid" style="max-height: 80vh;">
            </div>
        </div>
    </div>
</div>

<!-- 批量操作模态框 -->
<div class="modal fade" id="batchSettlementModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">批量结算订单</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您选择了 <span id="batchOrderCountDisplay" class="text-primary fw-bold">0</span> 个订单进行批量结算</p>
                
                <div class="mb-3">
                    <label for="staticSettlementType" class="form-label">结算类型</label>
                    <select class="form-select" id="staticSettlementType" name="settlement_type">
                        <option value="commission">结本金</option>
                        <option value="principal_commission" selected>结本金+佣金</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label for="staticSettlementAmount" class="form-label">结算金额</label>
                    <input type="number" class="form-control" id="staticSettlementAmount" name="settlement_amount" 
                           step="0.01" min="0" placeholder="留空则根据结算类型自动计算" value="">
                    <div class="form-text">如果留空，将根据下单自动计算金额</div>
                </div>
                
                <div class="mb-3">
                    <label for="staticSettlementInfo" class="form-label">结算信息</label>
                    <textarea class="form-control" id="staticSettlementInfo" name="settlement_info" 
                              rows="3" placeholder="请输入结算说明、备注等">批量结算操作</textarea>
                </div>
                
                <div class="mb-3">
                    <label for="staticSettlementScreenshots" class="form-label">结算截图（可选）</label>
                    <input type="file" class="form-control" id="staticSettlementScreenshots" name="settlement_screenshots[]" 
                           accept="image/*" multiple>
                    <div class="form-text">支持多张图片，格式：JPG、PNG、GIF，最大 5MB/张</div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="staticBatchSettlementConfirmBtn">
                    <i class="bi bi-check-circle"></i> 确认结算
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 订单详情模态框 -->
<div class="modal fade" id="orderDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">订单详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="orderDetailsContent">
                <!-- 详情内容将通过AJAX加载 -->
            </div>
        </div>
    </div>
</div>

<!-- 编辑订单模态框 -->
<div class="modal fade" id="editOrderModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">处理订单</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="editOrderContent">
                <!-- 编辑内容将通过AJAX加载 -->
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/footer.php'; ?>

<script>
let isProcessing = false;
let selectedOrders = [];

// 初始化选中状态
function initializeSelectedOrders() {
    selectedOrders = [];
    const checkboxes = document.querySelectorAll('.order-checkbox:checked');
    checkboxes.forEach(checkbox => {
        if (!selectedOrders.includes(checkbox.value)) {
            selectedOrders.push(checkbox.value);
        }
    });
    updateBatchButtons();
}

function toggleAllCheckboxes() {
    const checkAll = document.getElementById('checkAll');
    const checkboxes = document.querySelectorAll('.order-checkbox');
    
    checkboxes.forEach(checkbox => {
        checkbox.checked = checkAll.checked;
        if (checkAll.checked && !selectedOrders.includes(checkbox.value)) {
            selectedOrders.push(checkbox.value);
        } else if (!checkAll.checked) {
            selectedOrders = selectedOrders.filter(id => id !== checkbox.value);
        }
    });
    
    updateBatchButtons();
    saveSelectedOrders();
}

function toggleSelectAll() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.order-checkbox');
    
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAll.checked;
        if (selectAll.checked && !selectedOrders.includes(checkbox.value)) {
            selectedOrders.push(checkbox.value);
        } else if (!selectAll.checked) {
            selectedOrders = selectedOrders.filter(id => id !== checkbox.value);
        }
    });
    
    updateBatchButtons();
    saveSelectedOrders();
}

// 监听单个复选框变化
document.addEventListener('change', function(e) {
    if (e.target.classList.contains('order-checkbox')) {
        if (e.target.checked && !selectedOrders.includes(e.target.value)) {
            selectedOrders.push(e.target.value);
        } else if (!e.target.checked) {
            selectedOrders = selectedOrders.filter(id => id !== e.target.value);
        }
        updateBatchButtons();
        saveSelectedOrders();
    }
});

function updateBatchButtons() {
    const batchButtons = document.querySelectorAll('[onclick^="batch"]');
    batchButtons.forEach(button => {
        button.disabled = selectedOrders.length === 0;
    });
}

// 保存选中状态到sessionStorage
function saveSelectedOrders() {
    sessionStorage.setItem('selectedOrders', JSON.stringify(selectedOrders));
}

// 恢复选中状态
function restoreSelectedOrders() {
    const saved = sessionStorage.getItem('selectedOrders');
    if (saved) {
        selectedOrders = JSON.parse(saved);
        // 恢复复选框状态
        const checkboxes = document.querySelectorAll('.order-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = selectedOrders.includes(checkbox.value);
        });
        updateBatchButtons();
    }
}

// 页面加载时恢复选中状态
document.addEventListener('DOMContentLoaded', function() {
    restoreSelectedOrders();
    initializeSelectedOrders();
});

function showOrderDetails(orderId) {
    // 显示加载状态
    document.getElementById('orderDetailsContent').innerHTML = `
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-3">加载中...</p>
        </div>
    `;
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('orderDetailsModal'));
    modal.show();
    
    // 加载订单详情
    fetch('../api/order_details.php?id=' + orderId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const order = data.data;
                const statusClass = {
                    'pending': 'warning',
                    'settled': 'success',
                    'refunded': 'danger'
                };
                const statusText = {
                    'pending': '未结算',
                    'settled': '已结算',
                    'refunded': '已退还'
                };
                
                let html = `
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-sm">
                                <tr><td><strong>订单ID：</strong></td><td>${order.id}</td></tr>
                                <tr><td><strong>商品名称：</strong></td><td>${order.product_name}</td></tr>
                                <tr><td><strong>收货地：</strong></td><td>${order.delivery_location_label}</td></tr>
                                <tr><td><strong>下单平台：</strong></td><td>${order.order_platform_label}</td></tr>
                                <tr><td><strong>物流单号：</strong></td><td>${order.tracking_no}</td></tr>
                                <tr><td><strong>下单金额：</strong></td><td>¥${parseFloat(order.order_amount).toFixed(2)}</td></tr>
                                <tr><td><strong>付款方式：</strong></td><td>${order.payment_method_label}</td></tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-sm">
                                <tr><td><strong>订单状态：</strong></td><td>
                                    <span class="badge bg-${statusClass[order.status]}">${statusText[order.status]}</span>
                                </td></tr>
                                <tr><td><strong>签收状态：</strong></td><td>
                                    <span class="badge bg-${order.is_signed ? 'success' : 'warning'}">
                                        ${order.is_signed ? '已签收' : '未签收'}
                                    </span>
                                </td></tr>
                                <tr><td><strong>回款状态：</strong></td><td>
                                    <span class="badge bg-${order.is_refunded ? 'success' : 'secondary'}">
                                        ${order.is_refunded ? '已回款' : '未回款'}
                                    </span>
                                </td></tr>
                                <tr><td><strong>取件码：</strong></td><td>
                                    ${order.pickup_code ? `<span class="badge bg-info">${order.pickup_code}</span>` : '<span class="text-muted">无</span>'}
                                </td></tr>
                                <tr><td><strong>提交时间：</strong></td><td>${new Date(order.created_at).toLocaleString('zh-CN')}</td></tr>
                `;
                
                if (order.status === 'settled' && order.settlement_amount) {
                    html += `<tr><td><strong>结算金额：</strong></td><td class="text-success">¥${parseFloat(order.settlement_amount).toFixed(2)}</td></tr>`;
                }
                
                if (order.settlement_info) {
                    html += `<tr><td><strong>结算信息：</strong></td><td>${order.settlement_info.replace(/\n/g, '<br>')}</td></tr>`;
                }
                
                if (order.notes) {
                    html += `<tr><td><strong>备注信息：</strong></td><td>${order.notes.replace(/\n/g, '<br>')}</td></tr>`;
                }
                
                html += `
                            </table>
                        </div>
                    </div>
                `;
                
                if (order.order_screenshot) {
                    html += `
                        <div class="mt-4">
                            <h6>订单截图</h6>
                            <img src="${order.screenshot_url}" class="img-fluid rounded border" style="max-height: 300px;">
                        </div>
                    `;
                }
                
                document.getElementById('orderDetailsContent').innerHTML = html;
            } else {
                document.getElementById('orderDetailsContent').innerHTML = `
                    <div class="alert alert-danger">${data.message || '加载失败'}</div>
                `;
            }
        })
        .catch(error => {
            document.getElementById('orderDetailsContent').innerHTML = `
                <div class="alert alert-danger">加载失败：${error.message}</div>
            `;
        });
}

function editOrder(orderId) {
    console.log('编辑订单:', orderId);
    
    // 显示加载状态
    document.getElementById('editOrderContent').innerHTML = `
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-3">加载中...</p>
        </div>
    `;
    
    // 显示模态框
    const modalElement = document.getElementById('editOrderModal');
    const modal = new bootstrap.Modal(modalElement);
    modal.show();
    
    // 监听模态框完全显示事件
    modalElement.addEventListener('shown.bs.modal', function() {
        console.log('编辑模态框完全显示，重新绑定事件');
        
        // 重新绑定操作类型变化事件
        const operationType = document.getElementById('operation_type');
        const settlementFields = document.getElementById('settlementFields');
        
        if (operationType && settlementFields) {
            // 移除可能存在的旧事件监听器
            const newOperationType = operationType.cloneNode(true);
            operationType.parentNode.replaceChild(newOperationType, operationType);
            
            // 重新绑定事件
            newOperationType.addEventListener('change', function() {
                console.log('操作类型变化:', this.value);
                if (this.value === 'settle_principal' || this.value === 'settle_commission') {
                    settlementFields.style.display = 'block';
                    console.log('显示结算字段');
                } else {
                    settlementFields.style.display = 'none';
                    console.log('隐藏结算字段');
                }
            });
            
            // 立即执行一次
            if (newOperationType.value === 'settle_principal' || newOperationType.value === 'settle_commission') {
                settlementFields.style.display = 'block';
            } else {
                settlementFields.style.display = 'none';
            }
        }
    });
    
    // 加载订单编辑表单
    fetch('api/order_edit_form_new.php?id=' + orderId)
        .then(response => response.text())
        .then(html => {
            document.getElementById('editOrderContent').innerHTML = html;
            
            // 手动触发初始化
            setTimeout(() => {
                const operationType = document.getElementById('operation_type');
                const settlementFields = document.getElementById('settlementFields');
                
                if (operationType && settlementFields) {
                    console.log('手动初始化结算字段显示');
                    if (operationType.value === 'settle_principal' || operationType.value === 'settle_commission') {
                        settlementFields.style.display = 'block';
                    } else {
                        settlementFields.style.display = 'none';
                    }
                }
            }, 200);
        })
        .catch(error => {
            console.error('加载失败:', error);
            document.getElementById('editOrderContent').innerHTML = `
                <div class="alert alert-danger">加载失败：${error.message}</div>
            `;
        });
}

// 批量结算
function batchSettle() {
    if (selectedOrders.length === 0) {
        alert('请先选择要结算的订单');
        return;
    }
    
    // 更新订单数量显示
    document.getElementById('batchOrderCountDisplay').textContent = selectedOrders.length;
    
    // 重置表单
    document.getElementById('staticSettlementType').value = 'principal_commission';
    document.getElementById('staticSettlementAmount').value = '';
    document.getElementById('staticSettlementInfo').value = '无';
    document.getElementById('staticSettlementScreenshots').value = '';
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('batchSettlementModal'));
    modal.show();
}

// 绑定确认按钮事件 - 在页面加载时执行
document.addEventListener('DOMContentLoaded', function() {
    const confirmBtn = document.getElementById('staticBatchSettlementConfirmBtn');
    if (confirmBtn) {
        confirmBtn.addEventListener('click', function() {
            executeStaticBatchSettlement();
        });
    }
});

// 批量删除订单
function batchDelete() {
    if (selectedOrders.length === 0) {
        alert('请先选择要删除的订单');
        return;
    }
    
    if (confirm(`确定要删除选中的 ${selectedOrders.length} 个订单吗？此操作不可恢复！`)) {
        executeBatchOperation('delete');
    }
}

// 批量退还订单
function batchRefund() {
    if (selectedOrders.length === 0) {
        alert('请先选择要退还的订单');
        return;
    }
    
    if (confirm(`确定要将选中的 ${selectedOrders.length} 个订单标记为已退还吗？`)) {
        executeBatchOperation('refund');
    }
}

// 执行批量操作
function executeBatchOperation(action) {
    if (isProcessing) {
        showToast('正在处理中，请稍候...', 'warning');
        return;
    }
    
    isProcessing = true;
    
    const formData = new FormData();
    formData.append('action', action);
    formData.append('order_ids', JSON.stringify(selectedOrders));
    
    // 显示加载状态
    showToast(`正在执行批量${action === 'delete' ? '删除' : '退还'}操作...`, 'info');
    
    fetch('api/batch_operations.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        console.log('批量操作响应:', data);
        if (data.success) {
            showToast(data.message, 'success');
            
            // 清除选中状态
            selectedOrders = [];
            sessionStorage.removeItem('selectedOrders');
            document.getElementById('checkAll').checked = false;
            document.getElementById('selectAll').checked = false;
            document.querySelectorAll('.order-checkbox').forEach(cb => cb.checked = false);
            
            // 刷新页面
            setTimeout(() => {
                location.reload();
            }, 1500);
            
        } else {
            showToast(data.message, 'danger');
            if (data.errors && data.errors.length > 0) {
                console.error('批量操作错误:', data.errors);
                showToast('操作失败: ' + data.errors[0], 'danger');
            }
        }
    })
    .catch(error => {
        showToast('操作失败：' + error.message, 'danger');
        console.error('操作异常:', error);
    })
    .finally(() => {
        isProcessing = false;
    });
}

function executeStaticBatchSettlement() {
    if (isProcessing) {
        showToast('正在处理中，请稍候...', 'warning');
        return;
    }
    
    isProcessing = true;
    
    const settlementType = document.getElementById('staticSettlementType').value;
    const settlementAmount = document.getElementById('staticSettlementAmount').value;
    const settlementInfo = document.getElementById('staticSettlementInfo').value;
    const screenshotFiles = document.getElementById('staticSettlementScreenshots').files;
    
    const formData = new FormData();
    formData.append('action', 'settle');
    formData.append('order_ids', JSON.stringify(selectedOrders));
    formData.append('settlement_type', settlementType);
    
    // 只有当结算金额不为空时才添加
    if (settlementAmount && settlementAmount !== '') {
        formData.append('settlement_amount', parseFloat(settlementAmount));
    }
    
    formData.append('settlement_info', settlementInfo);
    
    // 添加截图文件
    if (screenshotFiles.length > 0) {
        for (let i = 0; i < screenshotFiles.length; i++) {
            formData.append('settlement_screenshots[]', screenshotFiles[i]);
        }
    }
    
    const confirmBtn = document.getElementById('staticBatchSettlementConfirmBtn');
    const originalText = confirmBtn.innerHTML;
    confirmBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 处理中...';
    confirmBtn.disabled = true;
    
    fetch('api/batch_operations.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast(data.message, 'success');
            
            // 清除选中状态
            selectedOrders = [];
            sessionStorage.removeItem('selectedOrders');
            document.getElementById('checkAll').checked = false;
            document.getElementById('selectAll').checked = false;
            document.querySelectorAll('.order-checkbox').forEach(cb => cb.checked = false);
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('batchSettlementModal'));
            if (modal) {
                modal.hide();
            }
            
            // 刷新页面以更新数据
            setTimeout(() => {
                location.reload();
            }, 1500);
            
        } else {
            showToast(data.message, 'danger');
            if (data.errors && data.errors.length > 0) {
                showToast('操作失败: ' + data.errors[0], 'danger');
            }
        }
    })
    .catch(error => {
        showToast('操作失败：' + error.message, 'danger');
    })
    .finally(() => {
        confirmBtn.innerHTML = originalText;
        confirmBtn.disabled = false;
        isProcessing = false;
    });
}

function exportOrders() {
    // 定义所有可导出的字段
    const exportFields = [
        { value: 'id', label: '订单ID' },
        { value: 'product_name', label: '商品名称' },
        { value: 'delivery_location', label: '收货地' },
        { value: 'order_platform', label: '下单平台' },
        { value: 'tracking_no', label: '物流单号' },
        { value: 'order_amount', label: '下单金额' },
        { value: 'payment_method', label: '付款方式' },
        { value: 'username', label: '用户名' },
        { value: 'phone', label: '手机号' },
        { value: 'group_name', label: '群组' },
        { value: 'is_registered', label: '登记状态' },
        { value: 'settlement_type', label: '结算类型' },
        { value: 'is_returned', label: '退还状态' },
        { value: 'is_signed', label: '签收状态' },
        { value: 'is_refunded', label: '回款状态' },
        { value: 'status', label: '订单状态' },
        { value: 'settlement_amount', label: '结算金额' },
        { value: 'created_at', label: '提交时间' },
        { value: 'updated_at', label: '更新时间' }
    ];
    
    // 生成字段选择HTML
    let fieldsHtml = '';
    exportFields.forEach((field, index) => {
        const checked = index < 8 ? 'checked' : ''; // 默认选中前8个常用字段
        fieldsHtml += `
            <div class="form-check form-check-inline col-md-3 mb-2">
                <input class="form-check-input export-field" type="checkbox" id="field_${field.value}" value="${field.value}" ${checked}>
                <label class="form-check-label" for="field_${field.value}">
                    ${field.label}
                </label>
            </div>
        `;
    });
    
    // 显示导出选项模态框
    const modalHtml = `
        <div class="modal fade" id="exportModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">导出订单</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">导出范围</label>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="exportType" id="exportAll" value="all" checked>
                                <label class="form-check-label" for="exportAll">
                                    导出所有结果
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="exportType" id="exportSelected" value="selected">
                                <label class="form-check-label" for="exportSelected">
                                    导出选中的订单 (<span id="selectedCount">${selectedOrders.length}</span>个)
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="exportType" id="exportFiltered" value="filtered">
                                <label class="form-check-label" for="exportFiltered">
                                    导出当前筛选结果
                                </label>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">导出格式</label>
                            <select class="form-select" id="exportFormat">
                                <option value="csv">CSV格式</option>
                                <option value="xlsx">Excel格式</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">选择要导出的字段</label>
                            <div class="border p-3" style="max-height: 300px; overflow-y: auto;">
                                <div class="row">
                                    ${fieldsHtml}
                                </div>
                            </div>
                            <div class="mt-2">
                                <button type="button" class="btn btn-sm btn-outline-primary" onclick="selectAllFields()">全选</button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearAllFields()">清空</button>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="confirmExport()">
                            <i class="bi bi-download"></i> 确认导出
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 添加到页面
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // 显示模态框
    const exportModal = new bootstrap.Modal(document.getElementById('exportModal'));
    exportModal.show();
    
    // 清理
    document.getElementById('exportModal').addEventListener('hidden.bs.modal', function() {
        this.remove();
    });
}

function selectAllFields() {
    const checkboxes = document.querySelectorAll('.export-field');
    checkboxes.forEach(cb => cb.checked = true);
}

function clearAllFields() {
    const checkboxes = document.querySelectorAll('.export-field');
    checkboxes.forEach(cb => cb.checked = false);
}

function confirmExport() {
    const exportType = document.querySelector('input[name="exportType"]:checked').value;
    const exportFormat = document.getElementById('exportFormat').value;
    
    // 获取选中的字段
    const selectedFields = [];
    const checkboxes = document.querySelectorAll('.export-field:checked');
    checkboxes.forEach(cb => {
        selectedFields.push(cb.value);
    });
    
    if (selectedFields.length === 0) {
        alert('请至少选择一个要导出的字段');
        return;
    }
    
    // 构建导出URL
    const params = new URLSearchParams(window.location.search);
    params.set('export_type', exportType);
    params.set('format', exportFormat);
    params.set('fields', selectedFields.join(','));
    
    if (exportType === 'selected' && selectedOrders.length > 0) {
        params.set('selected_orders', JSON.stringify(selectedOrders));
    }
    
    // 关闭模态框
    const modal = bootstrap.Modal.getInstance(document.getElementById('exportModal'));
    modal.hide();
    
    // 开始下载
    window.location.href = 'api/export_orders_new.php?' + params.toString();
}

function changePerPage(perPage) {
    const params = new URLSearchParams(window.location.search);
    params.set('per_page', perPage);
    params.set('page', '1'); // 重置到第一页
    window.location.href = '?' + params.toString();
}

function showImageModal(imageUrl) {
    document.getElementById('modalImage').src = imageUrl;
    const modal = new bootstrap.Modal(document.getElementById('imageModal'));
    modal.show();
}

// 图片放大功能 - 定义在全局作用域
function openImageModal(imageSrc) {
    console.log('打开图片模态框:', imageSrc);
    
    // 先移除可能存在的旧模态框和背景阴影
    const oldModal = document.getElementById('globalImageModal');
    const oldBackdrops = document.querySelectorAll('.modal-backdrop');
    
    if (oldModal) {
        oldModal.remove();
    }
    
    oldBackdrops.forEach(backdrop => {
        backdrop.remove();
    });
    
    // 移除 modal-open 类
    document.body.classList.remove('modal-open');
    document.body.style.overflow = '';
    document.body.style.paddingRight = '';
    
    // 创建模态框
    const modal = document.createElement('div');
    modal.id = 'globalImageModal';
    modal.className = 'modal fade';
    modal.innerHTML = `
        <div class="modal-dialog modal-xl modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">图片预览</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <img id="globalModalImage" src="" class="img-fluid" style="max-height: 70vh;">
                </div>
                <div class="modal-footer">
                    <a href="#" id="globalModalDownload" class="btn btn-primary" download>
                        <i class="bi bi-download"></i> 下载图片
                    </a>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-circle"></i> 关闭
                    </button>
                </div>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
    
    // 设置图片和下载链接
    const modalImage = document.getElementById('globalModalImage');
    const modalDownload = document.getElementById('globalModalDownload');
    
    if (modalImage) {
        modalImage.src = imageSrc;
        modalImage.alt = '预览图片';
    }
    
    if (modalDownload) {
        modalDownload.href = imageSrc;
        const filename = imageSrc.split('/').pop();
        modalDownload.download = filename;
        modalDownload.title = '下载: ' + filename;
    }
    
    // 显示模态框
    const bsModal = new bootstrap.Modal(modal);
    
    // 监听模态框隐藏事件，清理背景阴影
    modal.addEventListener('hidden.bs.modal', function() {
        console.log('模态框已隐藏，清理背景阴影');
        
        // 延迟清理，确保 Bootstrap 完成动画
        setTimeout(() => {
            // 移除背景阴影
            const backdrops = document.querySelectorAll('.modal-backdrop');
            backdrops.forEach(backdrop => {
                backdrop.remove();
            });
            
            // 恢复 body 样式
            document.body.classList.remove('modal-open');
            document.body.style.overflow = '';
            document.body.style.paddingRight = '';
            
            // 移除模态框元素
            if (modal && modal.parentNode) {
                modal.remove();
            }
        }, 150);
    });
    
    // 显示模态框
    bsModal.show();
}

// 为动态加载的内容绑定事件
function initDynamicContentEvents() {
    // 使用事件委托处理动态加载的图片点击
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('clickable-image')) {
            e.preventDefault();
            const imageSrc = e.target.getAttribute('data-src') || e.target.src;
            openImageModal(imageSrc);
        }
        
        // 处理按钮点击
        if (e.target.classList.contains('image-view-btn') || 
            (e.target.tagName === 'I' && e.target.closest('.image-view-btn'))) {
            e.preventDefault();
            const btn = e.target.classList.contains('image-view-btn') ? e.target : e.target.closest('.image-view-btn');
            const imageSrc = btn.getAttribute('data-src');
            if (imageSrc) {
                openImageModal(imageSrc);
            }
        }
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initDynamicContentEvents();
});

// 初始化工具提示
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl);
});
</script>
